package com.feng.rabbitmq.eight;

import com.feng.rabbitmq.utiils.RabbitMQUtils;
import com.rabbitmq.client.BuiltinExchangeType;
import com.rabbitmq.client.Channel;
import com.rabbitmq.client.DeliverCallback;

import java.util.HashMap;
import java.util.Map;

/**
 * 死信
 * 消费者
 */
public class Consumer01 {
    //普通的交换机
    public static final String NORMAL_EXCHANGE = "normal_exchange";

    //死信交换机
    public static final String DEAD_EXCHANGE = "dead_exchange";

    //普通队列
    public static final String NORMAL_QUEUE = "normal_queue";

    //死信队列
    public static final String DEAD_QUEUE = "dead_queue";

    public static void main(String[] args) throws Exception {
        Channel channel = RabbitMQUtils.getChannel();
        //声明死信和普通交换机 类型为direct
        channel.exchangeDeclare(DEAD_EXCHANGE, BuiltinExchangeType.DIRECT);
        channel.exchangeDeclare(NORMAL_EXCHANGE, BuiltinExchangeType.DIRECT);

        //正常队列变成死信队列的条件
        Map<String,Object> arguments = new HashMap<>();
        //过期时间 ms，这个在生产者中设置也可以
//        arguments.put("x-message-ttl",10000);
        //设置死信交换机
        arguments.put("x-dead-letter-exchange",DEAD_EXCHANGE);
        //设置死信routingKey
        arguments.put("x-dead-letter-routing-key","lisi");
        //设置正常队列的长度限制
//        arguments.put("x-max-length",6);

        //声明死信和普通队列
        channel.queueDeclare(DEAD_QUEUE,false,false,false,null);
        channel.queueDeclare(NORMAL_QUEUE,false,false,false,arguments);

        //绑定队列和交换机
        channel.queueBind(NORMAL_QUEUE,NORMAL_EXCHANGE,"zhangsan");
        channel.queueBind(DEAD_QUEUE,DEAD_EXCHANGE,"lisi");
        System.out.println("等待接收消息");

        DeliverCallback deliverCallback = (consumerTag, message) -> {
            //消息拒绝
            String msg = new String(message.getBody());
            if (msg.equals("5")){
                System.out.println("Consumer01接收的消息是："+msg+" 此消息被拒绝了");
                channel.basicReject(message.getEnvelope().getDeliveryTag(),false);
            }else {
                System.out.println("Consumer01接收的消息是："+new String(message.getBody()));
                channel.basicAck(message.getEnvelope().getDeliveryTag(),false);
            }
        };
        channel.basicConsume(NORMAL_QUEUE,false,deliverCallback,consumerTag -> {});

    }

}
